package com.china08.yxyapi.util;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 课程2.0工具类
 * 
 * @author Ertao.Fang
 *
 */
@Component
public class YxyKeChengUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyKeChengUtil.class);

    @Value("${salt.kecheng}")
    private String salt = "";

    @Value("${yxy.res.url}")
    private String yxy_res_url;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成课时播放地址
     * 
     * @param lessonItemId
     * @param userId
     * @return
     */
    public String genLessonItemPlayUrl(String lessonItemId, String userId) {
        String playUrl = ""//
                + yxy_res_url + "/res/browseKecheng/" + lessonItemId// 播放路径
                + "?" + genAuthQueryParamStr(lessonItemId, userId, false); // 授权签名
        return playUrl;
    }

    /**
     * 生成课时播放地址
     * 
     * @param lessonItemId
     * @param userId
     * @param userVip
     * @return
     */
    public String genLessonItemPlayUrl(String lessonItemId, String userId, Boolean userVip) {
        String playUrl = ""//
                + yxy_res_url + "/res/browseKecheng/" + lessonItemId// 播放路径
                + "?" + genAuthQueryParamStr(lessonItemId, userId, userVip); // 授权签名
        return playUrl;
    }

    /**
     * 生成课程授权查询参数字符串
     * 
     * @param lessonItemId
     * @param userId
     * @param userVip
     * @return
     */
    public String genAuthQueryParamStr( //
            String lessonItemId, //
            String userId, //
            Boolean userVip) {
        String authQueryParamStr = "";
        try {
            authQueryParamStr = genAuthQueryParamStr(lessonItemId, userId, userVip, System.currentTimeMillis());
        } catch (Exception e) {
            LOGGER.error("生成课程授权查询参数字符串失败", e);
        }
        return authQueryParamStr;
    }

    /**
     * 生成课程授权查询参数字符串
     * 
     * @param lessonItemId
     * @param userId
     * @param userVip
     * @param ts
     * @return
     * @throws Exception
     */
    public String genAuthQueryParamStr(//
            String lessonItemId, //
            String userId, //
            Boolean userVip, //
            Long ts//
    ) throws Exception {
        // ##
        // Salt
        String secretKey = DigestUtils.md5Hex(salt + ":" + lessonItemId + ":" + ts);

        // ##
        // TokeMap
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("ts", ts);
        tokenMap.put("userId", userId);
        tokenMap.put("userVip", userVip);
        tokenMap.put("lessonItemId", lessonItemId);

        // ##
        // TokenJsonStr
        String tokenJson = objectMapper.writeValueAsString(tokenMap);
        // ##
        // TokenEncrypted
        String tokenEncrypted = DESUtil.encryption(tokenJson, secretKey);
        // ##
        // TokenBase64
        String tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncrypted.getBytes());
        tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncryptedBase64.getBytes());
        tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncryptedBase64.getBytes());
        // ##
        // TokenBase64UrlEncoded
        String tokenEncryptedBase64UrlEncoded = URLEncoder.encode(tokenEncryptedBase64, "UTF-8");
        // ##
        // sign
        String sign = DigestUtils.md5Hex(tokenJson + ":" + secretKey);
        // ##
        // query string
        String queryParamStr = "" //
                + "token=" + tokenEncryptedBase64UrlEncoded + "&" //
                + "sign=" + sign + "&"//
                + "ts=" + ts;
        LOGGER.info("ts:" + ts);
        LOGGER.info("sign:" + sign);
        LOGGER.info("tokenJson:" + tokenJson);
        LOGGER.info("tokenEncrypted:" + tokenEncrypted);
        LOGGER.info("tokenEncryptedBase64:" + tokenEncryptedBase64);
        LOGGER.info("tokenEncryptedBase64UrlEncoded:" + tokenEncryptedBase64UrlEncoded);
        LOGGER.info("secretKey:" + secretKey);
        return queryParamStr;
    }

    // public static void main(String[] args) throws Exception {
    // String userId = "1234567890";
    // String lessonItemId = "2c908a1c5b47ec9a015b482975170000";
    // YxyKeChengUtil yxyKeChengUtil = new YxyKeChengUtil();
    // System.out.println(yxyKeChengUtil.genLessonItemPlayUrl(lessonItemId,
    // userId));
    // }

}
